const { Draft } = require('../models');
const { generateUniqueId } = require('../utils/authUtils');
const { validationResult } = require('express-validator');

// 创建或更新草稿
const saveDraft = async (req, res) => {
  try {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({ errors: errors.array() });
    }

    const { id, title, content } = req.body;
    const userId = req.user.id;

    // 如果提供了id，尝试更新现有草稿
    if (id) {
      const draft = await Draft.findOne({ where: { id, user_id: userId } });
      
      if (draft) {
        // 更新草稿
        await draft.update({ title, content, updated_at: new Date() });
        return res.status(200).json({ message: '草稿更新成功', draft });
      }
    }

    // 创建新草稿
    const draft = await Draft.create({
      id: generateUniqueId(),
      title: title || '未命名草稿',
      content,
      user_id: userId,
      created_at: new Date(),
      updated_at: new Date()
    });

    res.status(201).json({ message: '草稿保存成功', draft });
  } catch (error) {
    console.error('保存草稿失败:', error);
    res.status(500).json({ message: '服务器错误' });
  }
};

// 获取用户的草稿列表
const getUserDrafts = async (req, res) => {
  try {
    const userId = req.user.id;
    const { page = 1, limit = 10 } = req.query;
    
    const offset = (page - 1) * limit;

    const { count, rows: drafts } = await Draft.findAndCountAll({
      where: { user_id: userId },
      limit: parseInt(limit),
      offset: parseInt(offset),
      order: [['updated_at', 'DESC']]
    });

    res.status(200).json({
      drafts,
      total: count,
      page: parseInt(page),
      limit: parseInt(limit),
      totalPages: Math.ceil(count / limit)
    });
  } catch (error) {
    console.error('获取草稿列表失败:', error);
    res.status(500).json({ message: '服务器错误' });
  }
};

// 获取单个草稿
const getDraftById = async (req, res) => {
  try {
    const { id } = req.params;
    const userId = req.user.id;

    const draft = await Draft.findOne({
      where: { id, user_id: userId }
    });

    if (!draft) {
      return res.status(404).json({ message: '草稿不存在或无权限查看' });
    }

    res.status(200).json(draft);
  } catch (error) {
    console.error('获取草稿详情失败:', error);
    res.status(500).json({ message: '服务器错误' });
  }
};

// 删除草稿
const deleteDraft = async (req, res) => {
  try {
    const { id } = req.params;
    const userId = req.user.id;

    const result = await Draft.destroy({
      where: { id, user_id: userId }
    });

    if (result === 0) {
      return res.status(404).json({ message: '草稿不存在或无权限删除' });
    }

    res.status(200).json({ message: '草稿删除成功' });
  } catch (error) {
    console.error('删除草稿失败:', error);
    res.status(500).json({ message: '服务器错误' });
  }
};

// 将草稿发布为笔记
const publishDraft = async (req, res) => {
  try {
    const { id } = req.params;
    const userId = req.user.id;
    const { tags = [], images = [], categoryIds = [] } = req.body;

    // 查找草稿
    const draft = await Draft.findOne({
      where: { id, user_id: userId }
    });

    if (!draft) {
      return res.status(404).json({ message: '草稿不存在或无权限操作' });
    }

    // 导入Note相关模型
    const { Note, NoteTag, NoteImage, NoteCategory } = require('../models');

    // 创建笔记
    const note = await Note.create({
      id: generateUniqueId(),
      title: draft.title,
      content: draft.content,
      user_id: userId,
      created_at: new Date()
    });

    // 创建标签
    if (tags.length > 0) {
      const tagPromises = tags.map(tag => 
        NoteTag.create({ note_id: note.id, tag })
      );
      await Promise.all(tagPromises);
    }

    // 创建图片
    if (images.length > 0) {
      const imagePromises = images.map(imageUrl => 
        NoteImage.create({ note_id: note.id, image_url: imageUrl })
      );
      await Promise.all(imagePromises);
    }

    // 关联分类
    if (categoryIds.length > 0) {
      const categoryPromises = categoryIds.map(categoryId => 
        NoteCategory.create({ note_id: note.id, category_id: categoryId })
      );
      await Promise.all(categoryPromises);
    }

    // 可选：发布后删除草稿
    await draft.destroy();

    res.status(201).json({
      message: '草稿发布成功',
      noteId: note.id
    });
  } catch (error) {
    console.error('发布草稿失败:', error);
    res.status(500).json({ message: '服务器错误' });
  }
};

module.exports = {
  saveDraft,
  getUserDrafts,
  getDraftById,
  deleteDraft,
  publishDraft
};